
//获取价格间隔时间
last_id = 0;
$(function(){
title = document.title;
});
service_interval = 4000;
var base_currency = 'RMB';
//var target_currency = 'BTC';
var currency = {
  RMB : { symbol : '￥', unit : '元'},
  BTC : { symbol : '฿', unit : 'BTC'},
  LTC : { symbol : 'Ł', unit : 'LTC'}
}
var param = {
  fetchRate : 1,
  fetchUser : 0,
  fetchStatistic : 0,
  fetchSum : 0,
  sumLimit : 50,
  fetchTransaction : 0,
  transactionLimit : 20,
  transactionColumn : 'full',
  fetchBigOrder : 0, 
  bigOrderLimit : 5,
  bigOrderColumn : 'full'
}
var ajaxRequest = 0;

//坏数字
function badFloat(num, size){
  if(isNaN(num)) return true;
  num += '';
  if(-1 == num.indexOf('.')) return false;
  var f_arr = num.split('.');
  if(f_arr[1].length > size){
    return true;
  }
  return false;
}
//按钮效果
function tabFn(id, cn){
  var o=Dom(id), cls=o.className;
  o.onmouseover = function(){this.className=cn}
  o.onmouseout = function(){this.className=cls}
}
//浮层
function Maskfn(id){
  var MaskBg=Dom('MaskBg');
  Dom(id).onclick = function(){
    MaskBg.style.height = Math.max(document.body.offsetHeight, document.documentElement.clientHeight) + 'px';
    MaskBg.style.display = "block";
    Dom('Mask1').style.display = "block";
  }
  Dom('closeBtn').onclick = Dom('mBtn1').onclick = Dom('mBtn2').onclick = function(){
    MaskBg.style.display = "none";
    Dom('Mask1').style.display = "none";
  }
}
//格式化小数
function formatfloat(f, size){
  f += '';
  if(-1 == f.indexOf('.')) return (f = parseInt(f))? f: 0;

  var f_arr = f.split('.');
  if(f_arr[1].length > size){
    return parseFloat(parseFloat(f).toFixed(size));
  }
  return (f = parseFloat(f_arr[0] + '.' + f_arr[1])) ? f: 0;
}
//Dom
function Dom(o){
	return document.getElementById(o) ? document.getElementById(o) : false;
}
//ajax请求参数
function setParam(o){
  for(x in o){
    param[x] = o[x];
  }
  ajaxRequest = 1;
}
//总数据
function getData(){
  if(!ajaxRequest){
    return;
  }
  var bjsProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
  var uid = $("#uid").attr("value");
  var encryptionuid = $("#encryptionuid").attr("value");
  $.ajax({
      type : "GET",
      url : document.location.protocol+"//data.bijiaosuo.cn/getTradeInfo.php?uid=" + uid + "&encryptionuid=" + encryptionuid + "&callback=?",
     dataType : "jsonp",
     jsonp: 'callback',
     jsonpCallback:"jsonpCallback",
      success : function(r){
          responseHandler.run(r, function(handler) {
              if(r.user != undefined){
                updateDataUser(r.user, r.rate);
              }
              if(r.statistic != undefined){
                updateDataStatistic(r.statistic, r.rate);
              }
              if(r.sum != undefined){
                updateDataSum(r.sum, param.sumLimit);
              }
              if(r.transaction != undefined){
                updateDataTransaction(r.transaction, param.transactionColumn);
              }
              if(r.bigOrder != undefined){
                updateDataBigOrder(r.bigOrder, param.bigOrderColumn);
              }
            });
      }
  });

 
  gd = setTimeout("getData()", service_interval);
}
//用户
function updateDataUser(data, rate){
  var assets = 0;
  for(k in data.balance){
    Dom(k+'_balance').innerHTML = currency[k].symbol + formatfloat(data.balance[k], 5);
    Dom(k+'_pure_balance').innerHTML = formatfloat(data.balance[k], 5);
    //Dom(k+'_balance_unit').innerHTML = currency[k].unit;
    if(k == base_currency){
      assets += formatfloat(data.balance[k], 5);
    }else{
      assets += formatfloat(data.balance[k] * rate[k+'_'+base_currency], 5);
    }
  }
  for(k in data.frozen){
    Dom(k+'_frozen').innerHTML = currency[k].symbol + formatfloat(data.frozen[k], 5);
    //Dom(k+'_frozen_unit').innerHTML = currency[k].unit;
    if(k == base_currency){
      assets += formatfloat(data.frozen[k], 5);
    }else{
      assets += formatfloat(data.frozen[k] * rate[k+'_'+base_currency], 5);
    }
  }
  //calculate total assets
  //Dom(base_currency+'_total_assets').innerHTML = currency[base_currency].symbol + formatfloat(assets, 5);
  jQuery("."+base_currency+"_total_assets").html(currency[base_currency].symbol + formatfloat(assets, 2));
}
//价格
function updateDataStatistic(data, rate){
  var n = target_currency+'_'+base_currency;
  Dom('yesterday_close').innerHTML = data.yesterday_close;
  Dom('time').innerHTML = data.time;
  if(!data.today_open){
    Dom(n+'_rate').innerHTML = config.getString('Opening soon');
    if(Dom(n+'_rate_market')){
      Dom(n+'_rate_market').innerHTML = '-';
    }
    $('#price_arrow').removeClass();
    Dom('buy_price').innerHTML = '-';
    Dom('sell_price').innerHTML = '-';
    Dom('high_price').innerHTML = '-';
    Dom('low_price').innerHTML = '-';
    Dom('volume').innerHTML = '-';
    Dom('rise_limit').innerHTML = '-';
    Dom('fall_limit').innerHTML = '-';
    Dom('changed_price').innerHTML = '';
    Dom('changed_percent').innerHTML = '';
    Dom('today_open').innerHTML = '-';
    return;
  }
  var price = parseFloat(rate[n]).toFixed(2).split('.');
  Dom(n+'_rate').innerHTML = currency[base_currency].symbol + price[0];
  
  var statcPrice=jQuery('.'+n+'_rate').html();
  var nowstatcPrice=currency[base_currency].symbol + parseFloat(rate[n]).toFixed(2);
  if(statcPrice!=nowstatcPrice){
	   jQuery('.'+n+'_rate').effect('highlight', {}, 2000);
	} 
	jQuery('.'+n+'_rate').html(nowstatcPrice); //global site update
 
 
   //设置标题显示最新报价
    var pathname = window.location.pathname;
    var search = window.location.search;
    var href = pathname + search;
    switch (href) {
        case '/':
        case '/trade/in/rmb/btc.html':
		case '/site/index.html':
		var _title = '¥'+parseFloat(rate[n]).toFixed(2)+'-'+title;
		document.title = _title;
		break;
    }
	

  if(price[1]){
    Dom(n+'_rate').innerHTML += '<b>.'+price[1]+'</b>';
  }
  if(Dom(n+'_rate_market')){
    Dom(n+'_rate_market').innerHTML = currency[base_currency].symbol + price[0];
    if(price[1]){
      Dom(n+'_rate_market').innerHTML += '<b>.'+price[1]+'</b>';
    }
  }

  data.buy_price = parseFloat(data.buy_price);
  data.sell_price = parseFloat(data.sell_price);
  data.high_price = parseFloat(data.high_price);
  data.low_price = parseFloat(data.low_price);
  data.today_open = parseFloat(data.today_open);
  data.yesterday_close = parseFloat(data.yesterday_close);
  
  var buyPrice =jQuery('.buy_price').html();
  var nowbuyPrice =currency[base_currency].symbol + data.buy_price;
  if(buyPrice!=nowbuyPrice){
	   jQuery('.buy_price').effect('highlight', {}, 2000);
	  }
  Dom('buy_price').innerHTML = data.buy_price;
  jQuery('.buy_price').html( nowbuyPrice); //global site update

  var sellPrice=jQuery('.sell_price').html();
  var nowsellPrice = currency[base_currency].symbol + data.sell_price;
  if(sellPrice!=nowsellPrice){
	   jQuery('.sell_price').effect('highlight', {}, 2000);
	  }
  Dom('sell_price').innerHTML = data.sell_price;
  jQuery('.sell_price').html( currency[base_currency].symbol + data.sell_price); //global site update

  Dom('high_price').innerHTML = data.high_price;
  Dom('low_price').innerHTML = data.low_price;
  
  var volume=jQuery('.volume').html();
  var nowvolume = currency['BTC'].symbol + data.volume;
  if(volume!=nowvolume){
	   jQuery('.volume').effect('highlight', {}, 2000);
	  }
	  
  Dom('volume').innerHTML = data.volume;
  jQuery('.volume').html(currency['BTC'].symbol + data.volume); //global site update

  Dom('rise_limit').innerHTML = data.rise_limit;
  Dom('fall_limit').innerHTML = data.fall_limit;
  Dom('changed_price').innerHTML = data.changed_price;
  Dom('changed_percent').innerHTML = data.changed_percent + '%';
  if(data.changed_price > 0){
    Dom('changed_price').innerHTML = '+' + Dom('changed_price').innerHTML;
    Dom('changed_percent').innerHTML = '+' + Dom('changed_percent').innerHTML;
  }
  Dom('today_open').innerHTML = data.today_open;
  //color
  if(rate[n] > data.today_open){
    $('#'+n+'_rate').removeClass('buy sell gray').addClass('buy');
    $('#price_arrow').removeClass().addClass('arrow-large arrow-rise');
  }else if(rate[n] < data.today_open){
    $('#'+n+'_rate').removeClass('buy sell gray').addClass('sell');
    $('#price_arrow').removeClass().addClass('arrow-large arrow-fall');
  }else{
    $('#'+n+'_rate').removeClass('buy sell gray').addClass('gray');
    $('#price_arrow').removeClass().addClass('arrow-large arrow-normal');
  }

  if(data.today_open > data.yesterday_close){
    $('#today_open').removeClass('buy sell gray').addClass('buy');
  }else if(data.today_open < data.yesterday_close){
    $('#today_open').removeClass('buy sell gray').addClass('sell');
  }else{
    $('#today_open').removeClass('buy sell gray').addClass('gray');
  }

  if(Dom(n+'_rate_market')){
    if(rate[n] > data.today_open){
      $('#'+n+'_rate_market').removeClass('buy sell gray').addClass('buy');
    }else if(rate[n] < data.today_open){
      $('#'+n+'_rate_market').removeClass('buy sell gray').addClass('sell');
    }else{
      $('#'+n+'_rate_market').removeClass('buy sell gray').addClass('gray');
    }
  }

  if(data.changed_price > 0){
    $('#changed_price').removeClass('buy sell gray').addClass('buy');
    $('#changed_percent').removeClass('buy sell gray').addClass('buy');
  }else if(data.changed_price < 0){
    $('#changed_price').removeClass('buy sell gray').addClass('sell');
    $('#changed_percent').removeClass('buy sell gray').addClass('sell');
  }else{
    $('#changed_price').removeClass('buy sell gray').addClass('gray');
    $('#changed_percent').removeClass('buy sell gray').addClass('gray');
  }

  if(data.buy_price > data.today_open){
    $('#buy_price').removeClass('buy sell gray').addClass('buy');
  }else if(data.buy_price < data.today_open){
    $('#buy_price').removeClass('buy sell gray').addClass('sell');
  }else{
    $('#buy_price').removeClass('buy sell gray').addClass('gray');
  }

  if(data.sell_price > data.today_open){
    $('#sell_price').removeClass('buy sell gray').addClass('buy');
  }else if(data.sell_price < data.today_open){
    $('#sell_price').removeClass('buy sell gray').addClass('sell');
  }else{
    $('#sell_price').removeClass('buy sell gray').addClass('gray');
  }

  if(data.high_price > data.today_open){
    $('#high_price').removeClass('buy sell gray').addClass('buy');
  }else if(data.high_price < data.today_open){
    $('#high_price').removeClass('buy sell gray').addClass('sell');
  }else{
    $('#high_price').removeClass('buy sell gray').addClass('gray');
  }

  if(data.low_price > data.today_open){
    $('#low_price').removeClass('buy sell gray').addClass('buy');
  }else if(data.low_price < data.today_open){
    $('#low_price').removeClass('buy sell gray').addClass('sell');
  }else{
    $('#low_price').removeClass('buy sell gray').addClass('gray');
  }
}
//委托
function updateDataSum(data, limit){
  var with_scale = 1;
  for(var type in data){
    var d = data[type];
    var html = '';
    var idhtml = '';

    if(limit == 5 && type == 'sell'){
      var dmax = d.length > limit? limit: d.length;
    }
    var i = 1;
    for(var m=0;m<d.length;m++){
      var num = parseFloat(d[m][1]), width = num * with_scale > 100? 100: num * with_scale;
      if(type == 'buy'){
        idhtml = '<td class="buy">'+config.getString('buy')+'(' + (i) + ')</td>';
        html += '<tr class="trade-tr' + i + '" onclick="change_sell_form(this)">' + idhtml + '<td>'+ currency[base_currency].symbol + '<span class="sub_price">' + parseFloat(d[m][0]) + "</span>" + '</td><td>' +  '<font face="Tahoma">' + currency[target_currency].symbol + "</font>" + '<span class="sub_amount">' + num + "</span>" + '</td><td><span style="width:' + width + 'px" class="' + (type == 'buy'? 'sell': 'buy') + 'Span"></span></td></tr>';
      }else{
        idhtml = '<td class="sell">'+config.getString('sell')+'(' + (limit == 5 ? dmax-- : i) + ')</td>';
        html += '<tr class="trade-tr' + i + '" onclick="change_buy_form(this)" >' + idhtml + '<td>'+ currency[base_currency].symbol + '<span class="sub_price">' + parseFloat(d[m][0]) + "</span>" + '</td><td>' + '<font face="Tahoma">' + currency[target_currency].symbol + "</font>" + '<span class="sub_amount">' + num + "</span>" + '</td><td><span style="width:' + width + 'px" class="' + (type == 'buy'? 'sell': 'buy') + 'Span"></span></td></tr>';
      }
      i++;
    }
    $('#' + type + 'list').html(html);
  }
}
//成交
function updateDataTransaction(data, column){
  var html = '';
  var transactionLimit = $("#transactionLimit").attr("value");
  for(var i in data){
	if (i >= transactionLimit && transactionLimit >0){
		break;
	}  
    var s = data[i][1] == 1 ? 'buy' : 'sell';
    if(column == 'full'){
      html += '<tr><td>' + data[i][0] + '</td><td class="' + s + '">' + (data[i][1] == 1? config.getString('buyIn'): config.getString('sellOut')) +
        '</td><td class="' + s + '">'+currency[base_currency].symbol + formatfloat(data[i][2], 2) + '</td><td>' + '<font face="Tahoma">' + currency[target_currency].symbol + "</font>"+ formatfloat(data[i][3], 3) + '</td></tr>';
    }else{
      html += '<tr><td>' + data[i][0] + '</td><td class="' + s + '">'+currency[base_currency].symbol + formatfloat(data[i][2], 2) + '</td><td>' + '<font face="Tahoma">' + currency[target_currency].symbol + "</font>" + formatfloat(data[i][3], 3) + '</td>' +
        '</tr>';
    }
  }
  $('#transaction').html(html);
}
//
function updateDataBigOrder(data, column){
  var html = '';
  var bigorderLimit = $("#bigorderLimit").attr("value");
  for(var i in data){
	  if (i >= bigorderLimit && bigorderLimit >0){
			break;
		} 
    var s = data[i][1] == 1 ? 'buy' : 'sell';
    if(column == 'full'){
      html += '<tr><td>' + data[i][0] + '</td><td class="' + s + '">' + (data[i][1] == 1? config.getString('buyIn'): config.getString('sellOut')) +
        '</td><td class="' + s + '">'+currency[base_currency].symbol + formatfloat(data[i][2], 2) + '</td><td>' + '<font face="Tahoma">' + currency[target_currency].symbol + "</font>" + formatfloat(data[i][3], 3) + '</td></tr>';
    }else{
      html += '<tr><td>' + data[i][0] + '</td><td class="' + s + '">'+currency[base_currency].symbol + formatfloat(data[i][2], 2) + '</td><td>' + '<font face="Tahoma">' + currency[target_currency].symbol + "</font>" + formatfloat(data[i][3], 3) + '</td>' +
        '</tr>';
    }
  }
  $('#bigOrder').html(html);
}
//最大可买
function maxBuy(price, balance){
  price = formatfloat(price, 2);
  if(balance > 0 && price > 0){
    $('#max').html(formatfloat(balance / price, 2));
  }
}
//总价-buy
function sumprice(){
  var total = formatfloat(formatfloat(Dom('price').value, 2) * formatfloat(Dom('number').value, 3), 5);
  Dom('sumprice').innerHTML = Math.round(total * 100) / 100;
  return total;
}
//总价-sell
function sumpriceSell(){
  var total = formatfloat(formatfloat(Dom('priceSell').value, 2) * formatfloat(Dom('numberSell').value, 3), 5);
  Dom('sumpriceSell').innerHTML = Math.round(total * 100) / 100;
  return total;
}
//Fee
function getFee(source, target, balance){
  var total = sumprice();
  if(total > 0){
    $.post(config.url+'/api/getFee?t=' + Math.random(),
      {source : source, target : target, total : total},
      function(r){
        responseHandler.run(r, function(handler) {
          if(r.fee != undefined){
            $('#sumprice').html(total + ' + ' + formatfloat(r.fee, 5));
            var totalWithFee = parseFloat(total) + parseFloat(r.fee);
            if(totalWithFee <= parseFloat(balance)){
              $('#sumprice').removeClass().addClass('green');
            }else{
              $('#sumprice').removeClass().addClass('red');
            }
          }
        });
      },
      'json'
    );
  }
}
//验证价格
function vNum(o, len){
  if(badFloat(o.value, len))
    o.value=formatfloat(o.value, len, 0);
}

function setSumLimit(v){
  setParam({fetchSum : 1, sumLimit : v});
  window.clearTimeout(gd);
  getData();
}

function setTransactionLimit(v){
  setParam({fetchTransaction : 1, transactionLimit : v});
  window.clearTimeout(gd);
  getData();
}

var sid;
var txt;
var n = 60;

function countDown(){
  if(n <= 0){
    window.clearInterval(sid);
    $('#send-sms-btn').removeAttr('disabled');
    $('#send-sms-btn').html(txt);
    n = 60;
    return;
  }
  n = n - 1;
  $('#send-sms-btn').html(txt + ' ' + n.toString());
}

$(function(){
  //单币价格提示
  var pricemsg = '此出价为 1个币 的价格';
  function pricemsgfn(){if($(this).val()==pricemsg) $(this).attr('style', 'color:#000');$(this).val('');}
  $('#pricein').val(pricemsg); $('#pricein').bind('click', pricemsgfn);
  $('#priceout').val(pricemsg);$('#priceout').bind('click', pricemsgfn);
});

$(document).ready(function() {
	//set nav fouces
	var pathname = window.location.pathname;
	var firsturlpath=pathname.substr(1,5);
	switch (firsturlpath) {
        case 'trade':
		$('#nav_trade').attr("class","cur");
		 break;
        case 'accou':
		$('#nav_accou').attr("class","cur");
		break;
		case 'curre':
		$('#nav_curre').attr("class","cur");
		break;
		case 'conte':
		$('#nav_conte').attr("class","cur");
		break;
		default:
		$('#nav_index').attr("class","cur");
		break;
    }
	
  getData();
  if(typeof(isRealMobile) != 'undefined'){
    $('.sidebar .box').each(function(){
      $(this).children().slice(1).hide();
    });
    $('.sidebar .box .PlateTitle').each(function(){
      $(this).append('<div class="mr10 pull-right arrow"><i class="icon-chevron-down"></i></div>');
    });

    $('.sidebar .box .TitleBox').click(function(){
      $(this).parent().children().toggle();
      $(this).find('i').toggleClass('icon-chevron-down icon-chevron-up');
      $(this).show();
    });
  }

  txt = $('#send-sms-btn').html();
});